<template>
  <div v-show="isDashboard" class="socket">
    <b style="display: inline">WebSocket 连接：</b>
    <el-switch :disabled="reconnectError" @change="changeSocket" active-color="#071B40"
               v-model="socketToOpen"></el-switch>
    <p v-if="isConnected" class="tip">{{socketCount?'已连接，已接收推送'+socketCount+'次':'已连接，正在等待推送'}}</p>
    <p v-if="!reconnectError && !isConnected && reconnectCount" class="tip" style="color: #ff4949">
      正在尝试重连，已尝试{{reconnectCount}}次</p>
    <p v-if="reconnectError" class="tip" style="color: #ff4949">网络故障，请检查你的网络设置</p>
    <i v-if="(!reconnectError && !isConnected && reconnectCount)||(socketToOpen && !isConnected)"
       class="el-icon-loading"></i>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex'

  export default {

    name: 'socketHandler',
    data() {
      return {
        isDashboard: true,
        socketToOpen: false,
        socketCount: 0
      }
    },
    watch: {
      $route() {
        this.setWidth()
      },
      reconnectCount() {
        this.socketToOpen = this.isConnected;
      },
      isConnected() {
        this.socketToOpen = this.isConnected;
        this.socketCount = 0;
      },
      socketMessage() {
        this.socketCount++;
      }
    },
    computed: {
      ...mapGetters([
        'sidebar',
        'isConnected',
        'socketMessage',
        'reconnectCount',
        'reconnectError'
      ])
    },

    props: {
      isActive: {
        type: Boolean,
        default: false
      }
    },
    methods: {
      setWidth() {
        this.isDashboard = this.$route.name === 'Dashboard';
      },
      changeSocket(status) {
        if (!status) {
          this.$disconnect()
        } else {
          this.$connect()
        }
      },
      mounted() {
        this.setWidth();
      }
    }
  }
</script>

<style lang="scss" scoped>
  .socket {
    display: inline-block;
    margin-left: 50px;
    font-size: 14px;
    line-height: 50px;
    color: #77889f;
    float: left;

    .tip {
      display: inline;
      margin: 0 5px 0 10px;
    }
  }
</style>
